package com.tang.codec;

import com.tang.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 自定义译码器, 也就是接收消息解码的
 *
 * @author fulin.tang
 * @version V3.0
 * @since 2021/9/13 12:00
 */
public class ObjDecoder extends ByteToMessageDecoder {

    private final Class<?> genericClass;

    public ObjDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        if (in.readableBytes() < 4) { // 小于4行直接返回
            return;
        }
        in.markReaderIndex();//?
        int dataLength = in.readInt(); // ?
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        out.add(SerializationUtil.getInstance().deserialize(data, genericClass));
    }

}
